// utils/request.js
import { BASE_URL } from './config'

export default function request(options = {}) {
  const token = wx.getStorageSync('token') || '';
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url.startsWith('http') ? options.url : BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': options.contentType || 'application/json',
        ...(token ? { Authorization: 'Bearer ' + token } : {}),
        ...options.header,
      },
      timeout: options.timeout || 10000,

      success: (res) => {
        if (res.statusCode === 200 && (res.data.code === 0 || res.data.success)) {
          resolve(res.data);
        } else {
          // 不提示 toast，由调用方决定
          reject({
            message: res.data.errorMessage || res.data.message || '请求失败',
            raw: res
          });
        }
      },

      fail: (res) => {
        reject({
          message: res.errMsg || '网络请求失败',
          raw: res
        });
      },
    });
  });
}

